import React, { forwardRef, useImperativeHandle } from "react";
import { Form, Button, Col } from "antd";
import "./index.less";

const SearchForm = forwardRef(
  (props, ref) => {
    const { config, handleSearch, beforeSearch, onFieldsChange } = props;
    const [form] = Form.useForm();
    const getFields = () => {
      return config.map((item) => {
        return (
          <Col span={6} key={item.key}>
            <Form.Item
              key={item.key}
              name={item.key}
              rules={item.rules}
              style={{ marginBottom: "6px" }}
              label={item.name}
            >
              {item.slot}
            </Form.Item>
          </Col>
        );
      });
    };

    const emitSearch = (values) => {
      // beforeSearch用于处理一些特殊情况
      beforeSearch(values);
      handleSearch(values);
    };

    const initialValues = config.reduce(
      (prev, next) => ({
        ...prev,
        [next.key]: next.initialValue
      }),
      {}
    );

    useImperativeHandle(ref, () => ({
      // 重置搜索字段
      resetFields(field) {
        return field ? form.resetFields([...field]) : form.resetFields();
      }
    }));

    return (
      <Form
        form={form}
        initialValues={initialValues}
        onFieldsChange={onFieldsChange}
        layout="inline"
        onFinish={emitSearch}
        style={{ marginBottom: 10 }}
        labelCol={{
          span: 8,
        }}
      // wrapperCol={{
      //   span: 12,
      // }}
      >
        {getFields()}
        <Form.Item>
          <Button htmlType="submit" type="primary">
            搜索
          </Button>
          <Button
            style={{
              margin: "0 8px",
            }}
            onClick={() => {
              form.resetFields();
              handleSearch(initialValues);
            }}
          >
            重置
          </Button>
        </Form.Item>
      </Form>
    );
  }
);

SearchForm.defaultProps = {
  beforeSearch: () => { },
  onFieldsChange: () => { }
};

export default SearchForm;
